<template>
  <view style="padding: 19rpx; background: #fff">
    <u-form
      labelPosition="left"
      :model="userInfo"
      ref="uForm"
      label-width="150rpx"
    >
      <u-form-item label="头像：" prop="img" borderBottom>
        <!-- <view style="float: right; margin-top: 12rpx; margin-left: 12rpx"
          ><u-icon name="arrow-right"></u-icon
        ></view> -->

        <button
          style="float: right"
          class="avatar-wrapper"
          open-type="chooseAvatar"
          @chooseavatar="onChooseavatar"
        >
          <image :src="avatarimg" class="wx-avatar"></image>
          <!-- <u-icon style="margin-top: 12rpx" name="arrow-right"></u-icon> -->
        </button>
      </u-form-item>
      <u-form-item label="姓名：" prop="realName" borderBottom>
        <u-input
          id="input-id"
          v-model="userInfo.realName"
          placeholder="请输入姓名"
        ></u-input>
      </u-form-item>
      <!-- <u-form-item label="性别：" prop="sex">
        <picker
          @change="bindPickerChange"
          :value="index"
          :range="list"
          range-key="text"
        >
          <view style="background-color: white">{{ userInfo.sex }}</view>
        </picker>
      </u-form-item> -->
      <!-- <u-form-item label="地址：" prop="name" borderBottom>
        <co-address-picker @change="addressPickerChange">
          <view
            class="region-text left"
            :class="{ empty: !receivingLocation }"
            >{{ receivingLocation || '请选择地址' }}</view
          >
        </co-address-picker>
      </u-form-item> -->
      <u-form-item label="昵称：" prop="nickName" borderBottom>
        <input
          v-model="userInfo.nickName"
          type="nickname"
          class="usernickname"
          placeholder="请输入昵称"
          @blur="onblur"
        />
      </u-form-item>
      <u-form-item label="手机号：" prop="username" borderBottom>
        <text class="text">{{ userInfo.username }}</text>
      </u-form-item>
    </u-form>

    <u-button
      @click="submit"
      type="primary"
      :loading="subLoad"
      style="margin-top: 100rpx"
      :custom-style="customStyle"
      >提交</u-button
    >
  </view>
</template>

<script>
import { updateProxy } from '@/api/user.js'
import { apiUpload } from '@/api/common.js'
import ENV from '@/config/ENV.js'
// 文件上传url
export const UPLOAD_URL = ENV.apiBaseURL + '/v1/oss/upload'
export default {
  data() {
    return {
      customStyle: {
        background: '#fe6507'
      },
      subLoad: false,
      addressCode: [],
      receivingLocation: '',
      list: [
        {
          text: '男'
        },
        {
          text: '女'
        }
      ],

      cellLabelStyle: {
        fontSize: '30rpx',
        color: '#666'
      },
      cellValStyle: {
        fontSize: '30rpx'
      },
      cellLabelSty2: {
        fontSize: '30rpx',
        color: '#333'
      },
      userInfo: {},
      show: true,
      avatarimg: ''
    }
  },
  computed: {},
  created() {
    this.userInfo = this.deepCopy(this.$store.state.userInfo)
    // if (
    //   this.userInfo.provinceName != null &&
    //   this.userInfo.cityName != null &&
    //   this.userInfo.areaName != null
    // ) {
    //   this.receivingLocation = `${this.userInfo.provinceName}-${this.userInfo.cityName}-${this.userInfo.areaName}`
    //   this.addressCode = [
    //     this.userInfo.provinceNo,
    //     this.userInfo.cityNo,
    //     this.userInfo.areaNo
    //   ]
    // }
    // if (this.userInfo.sex == '') {
    //   this.userInfo.sex = this.list[0].text
    // }
    this.userInfo.headImg = this.userInfo.img
    this.userInfo.id = this.userInfo.proxyId * 1
    this.userInfo.agentName = this.userInfo.realName
    this.avatarimg =
      this.userInfo.img ||
      'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
  },
  methods: {
    onChooseavatar(e) {
      let that = this
      console.log('头像', e)
      this.avatarimg = e.detail.avatarUrl
      this.userInfo.img = this.avatarimg

      uni.uploadFile({
        url: UPLOAD_URL, //仅为示例，非真实的接口地址
        filePath: this.avatarimg,
        name: 'file', //自定义name
        fileType: 'image', //图片类型

        header: {
          Authorization: this.$store.getters.isLogin
            ? `Bearer ${this.$store.state.token}`
            : '',
          platform: 'weChat_applet',
          //请求头
          'Content-Type': 'multipart/form-data'
          // formData: {
          //   //请求中接口额外的参数
          //   file: this.avatarimg
          // }
        },
        success: (res) => {
          that.userInfo.img = JSON.parse(res.data).data.url
          console.log('that.userInfo', that.userInfo) //经自己服务器存储后，将地址返回到客户端。
        },
        fail: (err) => {
          console.log('errerrerrerrerrerrerrerrerrerr', err)
        },
        complete(cp) {
          console.log(cp)
        }
      })
    },
    onblur(e) {
      console.log('昵称', e)
      this.userInfo.nickName = e.detail.value
    },
    bindPickerChange(e) {
      this.userInfo.sex = this.list[e.detail.value].text
    },
    isObject(obj) {
      return typeof obj === 'object' && obj !== null
    },
    deepCopy(source) {
      if (!this.isObject(source)) return source //如果不是对象的话直接返回
      let target = Array.isArray(source) ? [] : {} //数组兼容
      for (var k in source) {
        if (source.hasOwnProperty(k)) {
          if (typeof source[k] === 'object') {
            target[k] = this.deepCopy(source[k])
          } else {
            target[k] = source[k]
          }
        }
      }
      return target
    },
    addressPickerChange(e) {
      this.receivingLocation = e.name.join('-')
      this.userInfo.siteArr = e.code
      this.userInfo.provinceNo = e.code[0]
      this.userInfo.provinceName = e.name[0]
      this.userInfo.cityNo = e.code[1]
      this.userInfo.cityName = e.name[1]
      this.userInfo.areaNo = e.code[2]
      this.userInfo.areaName = e.name[2]
      this.addressCode = e.code
    },
    submit() {
      console.log(this.userInfo)
      uni.showLoading({
        mask: true
      })
      this.subLoad = true
      if (this.userInfo.img == '') {
        this.$am_toast.error('请上传头像！')
        uni.hideLoading()
        this.subLoad = false
        return
      }
      if (this.userInfo.realName == '') {
        this.$am_toast.error('请输入姓名！')
        uni.hideLoading()
        this.subLoad = false
        return
      }
      // if (this.userInfo.sex == '') {
      //   this.$am_toast.error('请选择性别！')
      //   uni.hideLoading()
      //   this.subLoad = false
      //   return
      // }
      // if (this.addressCode.length == 0) {
      //   this.$am_toast.error('请选择地址')
      //   uni.hideLoading()
      //   this.subLoad = false
      //   return
      // }
      this.userInfo.id = this.userInfo.proxyId * 1
      this.userInfo.agentName = this.userInfo.realName
      this.userInfo.headImg = this.userInfo.img
      updateProxy(this.userInfo).then((res) => {
        if (res.data.code == 200) {
          uni.hideLoading()
          this.subLoad = false
          this.$store.dispatch('updateUserinfo')
          this.$am_toast.success('操作成功！')
          uni.navigateBack({
            delta: 1
          })
          // uni.navigateTo({
          //     url: 'pages/mine/userinfo'
          // })
        } else {
          this.subLoad = false
          uni.hideLoading()
          this.$am_toast.error('操作失败，请重新尝试！')
        }
      })
    },
    chooseImage() {
      console.log(22222)
      let that = this
      uni.chooseMedia({
        count: 1, //默认9
        mediaType: ['image'],
        sourceType: ['album'], //从相册选择
        sizeType: ['compressed'],
        success: (res) => {
          console.log(res, 'compressedcompressedcompressed')
          const tempFilePaths = res.tempFiles //图片临时数组
          console.log(tempFilePaths)
          uni.uploadFile({
            //请求的url接口地址
            url: UPLOAD_URL,
            // formData:{
            //     //请求中接口额外的参数
            //     id:'1385048044696801281'
            // },
            fileType: 'image', //图片类型
            filePath: tempFilePaths[0].tempFilePath, //哪张图片
            name: 'file', //对应接口的文件名称
            header: {
              //请求头
              'Content-Type': 'multipart/form-data'
            },
            success: (res) => {
              console.log(that.userInfo.img)
              that.userInfo.img = JSON.parse(res.data).data.url
              console.log(that.userInfo.img)
              //成功的回调
              //一般用于重新获取数据渲染页面
            },
            fail: (err) => {
              that.$am_toast.error('上传失败')
              //失败的回调
              console.log(err)
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.uni-input-border {
  padding: 0 10px;
  height: 35px;
  width: 100%;
  font-size: 14px;
  color: #666;
  border: 1px #e5e5e5 solid;
  border-radius: 5px;
  box-sizing: border-box;
}
.img {
  width: 100rpx;
  height: 100rpx;
  float: right;
}
.text {
  font-size: 28rpx;
  color: #303133;
}
.region-text {
  height: 40rpx;
  line-height: 40rpx;
  text-align: right;
  color: #333;
  &.empty {
    color: #ccc;
  }
}
.left {
  text-align: left !important;
}
.wx-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16px;
}
.avatar-wrapper {
  padding: 0 !important;
  border: none !important;
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: transparent;
}
</style>
